/*
 * autor:dustin
 * 
 * email:dushaobindoudou@gmail.com
 *
 *
 */
var wky_define = (function(win){

    var isString = function(obj){
        return Object.prototype.toString.call(obj) === "[object String]";
    }
    
    var trim = function(str){
        if (!isString(str)) {
            return str;
        }
        return str.replace(/^\s+|\s+$/, "");
    }
    
    var hasProperty = function(obj, property){
        if (!obj || !property) {
            return;
        }
        if (property in obj) {
            if (obj.hasOwnProperty(property)) {
                return true;
            }
        }
        return false;
    }
    
    //检测空间名字的合法性
    var checkValid = function(str){
        var v = /^[a-zA-Z_\$][\da-zA-Z_\$]*$/;
        return str && v.test(str);
    }
    //
    var define = function(namespace){
        var ns = namespace.split(".");
        var tmpNs = win, len = ns.length, i = 0;
        while (i < len) {
            var curNs = trim(ns[i]);
            if (!curNs || !checkValid(curNs)) {
                throw new Error("定义的有不可用的空间名字！");
                break;
            }
			if(hasProperty(tmpNs,curNs)){
				tmpNs = tmpNs[curNs];
			}
            else {
                tmpNs[curNs] = {};
                tmpNs = tmpNs[curNs];
            }
            i++;
        }
        return tmpNs;
    }
    
    
    return function(namespace, callback){
        if (!isString(namespace)) {
            return;
        }
        var obj = define(namespace);
        var addNew = callback && callback.call(obj, obj);
		var varName,varObj;
		if(!addNew){
			return;
		}
        if(hasProperty(addNew,"varName") && hasProperty(addNew,"varVal")){
			if(hasProperty(obj,addNew["varName"])){
				throw new Error("已经包含了该名字，请仔细查看!");
				return;
			}
			obj[addNew["varName"]] = addNew["varVal"];
		}
		return obj;
    }
})(window);
